package managedbean;

import util.enumeration.Country;
import exception.ExistException;
import java.io.Serializable;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import session.stateless.SystemMessagesLocal;
import session.stateless.TouristAccountManagerLocal;
import util.entityhelper.TouristAccountState;
import util.enumeration.Gender;
import util.localization.WebLocalization;

/**
 *
 * @author Swee Zhi
 */
@ManagedBean
@RequestScoped
public class TouristRegisterManagedBean implements Serializable {
    @EJB
    private TouristAccountManagerLocal touristAccountMgr;
    // display exception
    @EJB
    private SystemMessagesLocal systemMessages;
    
    private FacesContext ctx = FacesContext.getCurrentInstance();
    private WebLocalization localization;
    
    // use entity helpers to extract data (attribute extraction and formatting instead of entity in this open bean)
    private TouristAccountState touristAcctState;
    
    //  user preferred locale
    private String preferredLocale;
    
    // other fields from database
    private String username;
    private String password;
    private String confirmPassword;
    private String lastname;
    private String firstname;
    private String gender;
    private Date birthdate;
    private String country;
    private String locale;
    private String email;
    private String emailSecondary;
    
    private String statusPasswordLength;
    private String statusPasswordMatch;

    public TouristRegisterManagedBean() {
        /* LOCALIZATION */
        localization = new WebLocalization();
        preferredLocale = localization.getPreferredLocaleFromSession();
        /* END LOCALIZATION */
        
        
//        statusPasswordLength = systemMessages.getSystemMessage("TOURIST_ACCT_PASSWORD_LENGTH_LESS_THAN_6");
//        statusPasswordMatch = systemMessages.getSystemMessage("TOURIST_ACCT_PASSWORDS_NOT_MATCH");
    }
    
        public void registerTourist(ActionEvent event) {    
            // set language for all MANAGERS for all THROWABLE display exceptions in backend
            // to use this line everytime language changes
            touristAccountMgr.setSelectedLocale(preferredLocale);
            
        try {
            /* validations first */
            if (validateEmailFormat(username) == false) {
    //            String invalidEmail = validationMessages.getValidationMessage("INVALID_EMAIL");
                String invalidEmail = systemMessages.getSystemMessage("INVALID_EMAIL", preferredLocale);
                System.out.println(invalidEmail);
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, invalidEmail, ""));
            }
            else {
            
            // set language for all MANAGERS for all THROWABLE display exceptions in backend
            // to use this line everytime language changes
            touristAccountMgr.setSelectedLocale(preferredLocale);
            
            Gender g = Gender.valueOf(gender);
            Country c = Country.valueOf(country);
            // email = username
            touristAccountMgr.createTouristAccount(username, password, lastname, firstname, g, birthdate, c, locale, username, emailSecondary);

            // print success message
            String statusMessage = systemMessages.getSystemMessage("ACCOUNT_CREATION_SUCCESS", preferredLocale);
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, statusMessage, ""));
            }
        }
        catch (ExistException ex) {
            // display exception
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage(), ""));
        }
        catch (Exception ex) {
            // display exception tp user
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage(), ""));
            // backend message for Tcube
            ex.printStackTrace();   
        }
    }
        
    
    public boolean validateEmailFormat(String emailInput) {
        Pattern p = Pattern.compile(".+@.+\\.[a-z]+");
        Matcher m = p.matcher(emailInput);
        boolean matchFound = m.matches();

        if (!matchFound) {
            // means error
            return false;
        }
        return true;
    }
    
    public void checkUsernameAvailability(ActionEvent event) {
        try {
            // set language for all MANAGERS for all THROWABLE display exceptions in backend
            // to use this line everytime language changes
            touristAccountMgr.setSelectedLocale(preferredLocale);
            
            touristAcctState = touristAccountMgr.getTouristAccountByUsername(username);
            
            if (touristAcctState == null) {
                // print ok message
                String statusMessage = systemMessages.getSystemMessage("USERNAME_OK", preferredLocale);
                FacesContext.getCurrentInstance().addMessage(username, new FacesMessage(FacesMessage.SEVERITY_INFO, statusMessage, ""));
            }
            else {
                // print error message
                String statusMessage = systemMessages.getSystemMessage("USERNAME_NOT_OK", preferredLocale);
                FacesContext.getCurrentInstance().addMessage(username, new FacesMessage(FacesMessage.SEVERITY_ERROR, statusMessage, ""));
            }
        }
        catch (ExistException ex) {
            // display exception
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage(), ""));
        }
        catch (Exception ex) {
            // display exception tp user
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage(), ""));
            // backend message for Tcube
            ex.printStackTrace();   
        }
    }

    public TouristAccountManagerLocal getTouristAccountMgr() {
        return touristAccountMgr;
    }

    public void setTouristAccountMgr(TouristAccountManagerLocal touristAccountMgr) {
        this.touristAccountMgr = touristAccountMgr;
    }

    public Date getBirthdate() {
        return birthdate;
    }

    public void setBirthdate(Date birthdate) {
        this.birthdate = birthdate;
    }

    public FacesContext getCtx() {
        return ctx;
    }

    public void setCtx(FacesContext ctx) {
        this.ctx = ctx;
    }
    
    public String getConfirmPassword() {
        return confirmPassword;
    }

    public void setConfirmPassword(String confirmPassword) {
        this.confirmPassword = confirmPassword;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getStatusPasswordLength() {
        return statusPasswordLength;
    }

    public void setStatusPasswordLength(String statusPasswordLength) {
        this.statusPasswordLength = statusPasswordLength;
    }

    public String getStatusPasswordMatch() {
        return statusPasswordMatch;
    }

    public void setStatusPasswordMatch(String statusPasswordMatch) {
        this.statusPasswordMatch = statusPasswordMatch;
    }

    public SystemMessagesLocal getSystemMessages() {
        return systemMessages;
    }

    public void setSystemMessages(SystemMessagesLocal systemMessages) {
        this.systemMessages = systemMessages;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getLocale() {
        return locale;
    }

    public void setLocale(String locale) {
        this.locale = locale;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getEmailSecondary() {
        return emailSecondary;
    }

    public void setEmailSecondary(String emailSecondary) {
        this.emailSecondary = emailSecondary;
    }

    public String getPreferredLocale() {
        return preferredLocale;
    }

    public void setPreferredLocale(String preferredLocale) {
        this.preferredLocale = preferredLocale;
    }

    public WebLocalization getLocalization() {
        return localization;
    }

    public void setLocalization(WebLocalization localization) {
        this.localization = localization;
    }
    
}
